# -*- coding: UTF-8 -*-
import sys
import web
import commons.util as util
import commons.dbutil as db

sys.path.append("/home/yeef/coding/diaryPy/trunk/diarpyProject/src")

domain = "http://yeef.webhop.net/"
page_path = "/usr/home/yeef/coding/diaryPy/trunk/pages/"


conn_cfg =  {    "host":    "localhost:5432",
                "user":     "postgres",
                "passwd":   "0573",
                "db":       "diary_db"
            }

tb_diary =  {   "name":     "diary",                                        # 表名
                "fields":   "id title content create_time read_count draft_flag tag",      # 字段列表
                "idseq":    "diary_id_seq",                                 # 自增ID序列名
                "format":   "dsssdds",                                        # 各字段的类型 (d表示int, s表示string)
                "defaults": ( 0, '', '', '', 0 ,1,'')                            # 各字段的默认值
            }

tb_tag = {  "name"      :   "tag",
            "fields"    :   "id diary_id tag_name",
            "idseq"     :   "tag_id_seq",
            "format"    :   "dds",
            "defaults"  :   (0,0,'')
        }

urls=(
        '/','index',
        '/diaryList','diaryList',
        '/displayDraft','displayDraft',
        '/diaryListByTag','diaryListByTag',
        '/deleteDiary','deleteDiary',
        '/insertDb','insertDb',
        '/updateDb', 'updateDb',
        '/readDiary','readDiary',
        '/editNewDiary','editNewDiary',
        '/search','search',
        '/deleteMore','deleteMore'
        
    )

def queryByLatest(draft,numLimit,jumpNumber):

    SQL='''SELECT id,title,content,create_time,read_count,tag
                FROM diary
                        WHERE draft_flag=%d
                                ORDER BY id DESC
                                        LIMIT %d   OFFSET %d'''

    conn=db.getconn(conn_cfg)
    results=db.query(conn, SQL, params=[draft,numLimit,jumpNumber], fields="id title content create_time read_count tag")
    db.submit(conn)

    return results


def queryByLike(key_word):

    SQL="SELECT id,title,content,create_time,read_count FROM diary WHERE content LIKE %s OR title LIKE %s "

    conn=db.getconn(conn_cfg)

    P1='%'+key_word+'%'
    P2='%'+key_word+'%'

    results=db.query(conn, SQL, params=[P1,P2],fields="id title content create_time read_count")

    db.submit(conn)

    return results


#===============================unused========================================================
def queryByTag(tag):

    SQL="SELECT id,title,content,create_time,read_count FROM diary WHERE tag LIKE %s"

    conn=db.getconn(conn_cfg)

    tag="% "+tag+" %"
    
    results=db.query(conn, SQL, params=[tag], fields="id title content create_time read_count")

    db.submit(conn)

    return results
#===============================unused==========================================================


def queryByTag_tb(tag):

    SQL="SELECT diary_id FROM tag WHERE tag_name=%s"

    conn=db.getconn(conn_cfg)

    results=db.query(conn, SQL, params=[tag], fields="diary_id")

    db.submit(conn)

    return results


def queryTagDelete(id):

    SQL="DELETE FROM tag WHERE diary_id=%d ;SELECT 1"

    conn=db.getconn(conn_cfg)

    results=db.query(conn, SQL, params=[id], fields="1")

    db.submit(conn)

    return results


def queryDiaryId():

    SQL="SELECT id FROM tag"

    conn=db.getconn(conn_cfg)

    results=db.query(conn, SQL, params=[], fields="id")

    db.submit(conn)

    return results


def queryTagFromTag_td():

    SQL="SELECT DISTINCT tag_name FROM tag ORDER BY tag_name"

    conn=db.getconn(conn_cfg)

    results=db.query(conn,SQL,params=[],fields="tag_name")

    db.submit(conn)
    
    for x in results:
        if x.tag_name=="":
            results.remove(x)
    return  results
def queryCountTags(tag):

    SQL="SELECT COUNT(tag_name) FROM tag WHERE tag_name=%s"

    conn=db.getconn(conn_cfg)

    results=db.query(conn,SQL,params=[tag],fields="count")

    db.submit(conn)

    return results[0].count

def queryAllDiarys():

    SQL='''SELECT COUNT(id) FROM diary'''

    conn=db.getconn(conn_cfg)

    results=db.query(conn,SQL,params=[],fields="count")

    db.submit(conn)

    return results[0].count

def deleteById(id):

    conn=db.getconn(conn_cfg)
    db.delete(conn, tb_diary, id)
    db.submit(conn)




def create_u(newDiary):

    conn=db.getconn(conn_cfg)

    aDiary=util.getObj()
    tags=util.getObj()

    aDiary.title=newDiary.title
    aDiary.content=newDiary.content
    aDiary.create_time='now()'
    aDiary.draft_flag=newDiary.draft_flag
    aDiary.tag=newDiary.tag

    db.create(conn, tb_diary, aDiary)

    SQL="SELECT MAX(id) FROM diary"
    maxID = db.query(conn,SQL,params=[], fields="id")
    maxid_num = maxID[0].id

    tagList=newDiary.tags.split(' ')

    for echoTag in tagList:
        tags.tag_name=echoTag
        tags.diary_id=maxid_num

        db.create(conn, tb_tag, tags)


    db.submit(conn)


def createTag(newTag):

    conn=db.getconn(conn_cfg)

    aTag=util.getObj()

    aTag.tag_name=newTag.tag_name
    aTag.diary_id=newTag.diary_id

    db.create(conn, tb_tag, aTag)
    db.submit(conn)


def readById(id):

    conn=db.getconn(conn_cfg)

    results=db.read(conn, tb_diary,id)
    db.submit(conn)

    return results


def updateById(newDiary):

    conn=db.getconn(conn_cfg)

    aDiary=util.getObj()
    aDiary.id=newDiary.id
    aDiary.title=newDiary.title
    aDiary.content=newDiary.content
    aDiary.create_time=newDiary.create_time
    aDiary.tag=newDiary.tag
    
    db.save(conn,tb_diary,aDiary)
    db.submit(conn)


def change(text):

    safe=text.replace("\n","<br>")
    safe=safe.replace("  ","&nbsp; ")
    return safe


def htmlSafe(text):

    safe=text.replace("<","&lt;")
    safe=safe.replace(">","&gt;")
    return safe





class index:

    def GET(self): 
        objs=util.getObj()
        objs.name = 'TIANCAI'
        objs.test_chinese = u"我是天才"
        return util.mako(objs, page_path, 'index')


class editNewDiary:

    def GET(self):
        obj=None
        return util.mako(obj, page_path, 'diary_note')


class diaryList:

    def GET(self):
        params=web.input()

        maxLimit=int(getattr(params, "max", 50))
        page=int(getattr(params,'page',1))

        jumpNumber=maxLimit*(page-1)

        objs=util.getObj()
        
        diary=queryByLatest(1,maxLimit,jumpNumber)

        for timeFormat in diary:
            timeFormat.create_time=util.fmtDate(timeFormat.create_time , 'MEDIUM')
            tags=timeFormat.tag.split(' ')
            tagsforUrl = []
            for t in tags:
                t = web.urlquote(t)
                tagsforUrl.append(t)
            timeFormat.tag=tags
            timeFormat.tagsforUrl=tagsforUrl

        objs.A=diary

        tags=queryTagFromTag_td()
        for eachTag in tags:
            tagname = eachTag.tag_name
            eachTag.tag_name_url = web.urlquote(tagname)
            
            eachTag.count= queryCountTags(tagname)
        objs.tag=tags

        allDiarys=int(queryAllDiarys())

        allPages=allDiarys/maxLimit
        x=allDiarys%maxLimit
        if allDiarys%maxLimit!=0:
            allPages=allPages+1
        else:
            allPages=allPages

        if page>=1 and page<allPages and allPages!=1:
            hasNextPage=True
        elif page==allPages:
            hasNextPage=False

        if page<=allPages and allPages>1 and page!=1:
            hasPrePage=True
        elif page==1:
            hasPrePage=False

        if hasNextPage==True:
            nextPage=page+1
        else:
            pass;

        if hasPrePage==True:
            prePage=page-1
        else:
            prePage=page

        objs.nextPage=nextPage
        objs.prePage=prePage
        objs.totil=allPages
        objs.nowPage=page
        objs.hasPrePage=hasPrePage
        objs.hasNextPage=hasNextPage
        objs.x=x
        return util.mako(objs, page_path, 'display')



class displayDraft():

    def GET(self):

        params=web.input()
        maxLimit=int(getattr(params, "max", 20))
        objs=util.getObj()
        diary=queryByLatest(0,maxLimit,0)

        for timeFormat in diary:
            timeFormat.create_time=util.fmtDate(timeFormat.create_time , 'MEDIUM')
           
        objs.A=diary


        return util.mako(objs, page_path, 'draft')


class diaryListByTag:

    def GET(self):
        obj=util.getObj()
        params=web.input()

        tagGet=getattr(params,'tag','')

        diary_id_list=queryByTag_tb(tagGet)

        result=[]
        for diary_id in diary_id_list:
            x=readById(diary_id.diary_id)
            if  hasattr(x,'__isNull__'):
                pass;
            else:
                result.append(x)

        #tag=queryByTag(tagGet)
        for timeFormat in result:
            timeFormat.create_time=util.fmtDate(timeFormat.create_time , 'MEDIUM')
        obj.A=result

        return util.mako(obj, page_path, 'diaryListByTag')





class deleteDiary:

    def GET(self):
        params=web.input()
        deleteId=int(getattr(params,"id",0))

        if deleteId==0:
            return "NOTHING TO DELETE"
        else:
            deleteById(deleteId)
            queryTagDelete(deleteId)
            web.seeother(domain+"diarypy/app.py/diaryList")


class deleteMore:

    def POST(self):
        params=web.input(diary_id=['0'])

        params_id=params.diary_id
        
        for x in params_id:
            if x=='0':
                
                web.seeother(domain+"diarypy/app.py/diaryList")

                
            else:
                deleteById(int(x))
                queryTagDelete(int(x))
            web.seeother(domain+"diarypy/app.py/diaryList")


class insertDb:

    def POST(self):
        params=web.input()

        draft_flag=getattr(params,"draft",1)
        tags=getattr(params,'tag',' ')
        title=params.title
        content=params.content
        content=htmlSafe(content)
        
        obj=util.getObj()
        

        obj.title=title
        obj.content=content
        obj.create_time='now()'
#       obj.tag=" "+tags+" "
        obj.tag=tags          # insert into diary table
        obj.tags=tags         #insert into tag table

        if draft_flag=='0':
            obj.draft_flag=0

            create_u(obj)
        else:
            obj.draft_flag=1

            create_u(obj)

       


        
        web.seeother(domain+"diarypy/app.py/diaryList")



class updateDb:

    def GET(self):
        objs=util.getObj()

        params=web.input()
        id=int(getattr(params,"id",0))

        if id==0:

            return "nothing to update"

        else:

            results=readById(id)
          

            return util.mako(results, page_path, 'displayAndUpdate')

    def POST(self):

        params=web.input()
        title=params.title
        content=params.content
        create_time=params.create_time
        id=int(params.id)
        tag=getattr(params,'tag',' ')


        content=htmlSafe(content)
        
        objs=util.getObj()
        tagObj=util.getObj()

        objs.title=title
        objs.content=content
        objs.create_time=create_time
        objs.id=id
        objs.tag=tag
        
        updateById(objs)
        queryTagDelete(id)
        
        tagObj.diary_id=id

        for echoTag in tag.split(' '):

            tagObj.tag_name=echoTag
            createTag(tagObj)

        web.seeother(domain+"diarypy/app.py/diaryList")
        
       


class readDiary:

    def GET(self):

        conn=db.getconn(conn_cfg)

        params=web.input()

        id=int(getattr(params,'id','0'))

        if id==0:

            return "Nothing To Read"

        else:
            result=util.getObj()
            results=readById(id)
            result.content=change(results.content)

            objs=util.getObj()

            objs.title=results.title
            objs.content=result.content
            objs.create_time=results.create_time
            objs.id=results.id
            objs.read_count=results.read_count
            
            results.read_count=results.read_count+1
            
            db.save(conn,tb_diary, results)
            db.submit(conn)

            return util.mako(objs, page_path, 'readDetial')


class search:

    def GET(self):
        return self.POST()

    def POST(self):

        params=web.input()
        obj=util.getObj()
        keyWord=params.keyword
        
        if keyWord=="":
            return "Please Enter The Key Words."
        else:
            results=queryByLike(keyWord)

            obj.A=results
            return util.mako(obj,page_path,'search')

application = web.application(urls, globals()).wsgifunc()
